package com.neusoft.aclome.cmp.cloud.server.jcce.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.neusoft.aclome.cmp.cloud.server.jcce.constants.DataResourceFileType;
import com.neusoft.aclome.cmp.cloud.server.jcce.constants.ProprietorshipStatusEnum;
import com.neusoft.aclome.cmp.cloud.server.jcce.constants.ResourceApplyStatusEnum;
import com.neusoft.aclome.cmp.cloud.server.jcce.dto.request.ConsultProcessRequest;
import com.neusoft.aclome.cmp.cloud.server.jcce.dto.response.ConsultProcessDTO;
import com.neusoft.aclome.cmp.cloud.server.jcce.dto.response.DataResourceDTO;
import com.neusoft.aclome.cmp.cloud.server.jcce.dto.response.UserResourceApplyDTO;
import com.neusoft.aclome.cmp.cloud.server.jcce.service.ConsultProcessService;
import com.neusoft.aclome.cmp.cloud.server.jcce.service.DataResourceService;
import com.neusoft.aclome.cmp.cloud.server.jcce.service.JcceKT1Service;
import com.neusoft.aclome.cmp.cloud.server.pub.cloud.constants.PubApi;
import com.neusoft.aclome.cmp.cloud.server.pub.cloud.exception.AclomeCloudPlatformException;
import com.neusoft.aclome.cmp.cloud.server.service.ToolsService;
import com.neusoft.aclome.cmp.common.model.vo.HttpResponse;
import com.neusoft.aclome.cmp.common.model.vo.ResponsePage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ResourceLoader;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

@Api("JcceKT1Controller")
@RequestMapping("/jcce" + PubApi.VERSION + "/kt1")
@RestController
public class JcceKT1Controller {

    private static final Logger log = LoggerFactory.getLogger(JcceKT1Controller.class);

    @Autowired
    private JcceKT1Service kt1Service;

    @Autowired
    private ConsultProcessService consultProcessService;
    @Autowired
    private DataResourceService dataResourceService;

    @Autowired
    private ToolsService toolsService;
    /**
     * 数据资源文件存储桶地址
     */
    private static final String bucketName = "data-resource";

    @GetMapping("/overview")
    @ApiOperation("云商列表概览")
    public HttpResponse overview() {
        return kt1Service.overview();
    }

    @GetMapping("/overview2")
    @ApiOperation("云商列表概览2")
    public HttpResponse overview2() {
        return kt1Service.overview2();
    }

    @GetMapping("/vms")
    @ApiOperation("实例")
    public HttpResponse vms(@RequestParam Integer dataCenterId) {
        return kt1Service.vms(dataCenterId);
    }

    @GetMapping("/volumns")
    @ApiOperation("磁盘")
    public HttpResponse volumns(@RequestParam Integer dataCenterId) {
        return kt1Service.volumns(dataCenterId);
    }

    @GetMapping("/rds")
    @ApiOperation("数据库")
    public HttpResponse rds(@RequestParam Integer dataCenterId) {
        return kt1Service.rds(dataCenterId);
    }

    @PostMapping("/dataResource")
    @ApiOperation("创建数据资源")
    public HttpResponse createDataResource(@ApiParam(value = "数据文件", required = false) MultipartFile dataFile,
                                           @ApiParam(value = "证明文件", required = false) MultipartFile proofFile,
                                           @ApiParam(value = "封面图片", required = false) MultipartFile imageFile,
                                           @ApiParam(value = "数据资源名称", required = true) @RequestParam("dataResourceName") String dataResourceName,
                                           @ApiParam(value = "用户id", required = true) @RequestParam("userId") String userId,
                                           @ApiParam(value = "使用权状态：待确认-PENDING，确权中-CONFIRMING，已通过-APPROVED，驳回-REJECTED", required = true) @RequestParam("proprietorshipStatus") ProprietorshipStatusEnum proprietorshipStatus,
                                           @ApiParam(value = "价格", required = false) @RequestParam(value = "price", required = false) BigDecimal price,
                                           @ApiParam(value = "数据类型", required = true) @RequestParam(value = "dataType") String dataType,
                                           @ApiParam(value = "数据分类", required = true) @RequestParam(value = "dataCategory") String dataCategory,
                                           @ApiParam(value = "证明文件类型", required = false) @RequestParam(value = "proofType", required = false) String proofType,
                                           @ApiParam(value = "使用权明细", required = false) @RequestParam(value = "usageRightDetail", required = false) String usageRightDetail,
                                           @ApiParam(value = "描述", required = false) @RequestParam(value = "description", required = false) String description) throws IOException {

        List<MultipartFile> list = new ArrayList<>();
        String originalDataFileName = "";
        String newDataFileName = "";
        if (dataFile != null && !dataFile.isEmpty()) {
            originalDataFileName = dataFile.getOriginalFilename();

            newDataFileName = FilenameUtils.getBaseName(dataFile.getOriginalFilename()).concat(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())) + "." + FilenameUtils.getExtension(dataFile.getOriginalFilename());
            MultipartFile multipartDataFile = new MockMultipartFile(newDataFileName, newDataFileName, dataFile.getContentType(), dataFile.getInputStream());
            list.add(multipartDataFile);
        }

        String originalProofFileName = "";
        String newProofFileName = "";
        if (proofFile != null && !proofFile.isEmpty()) {
            originalProofFileName = proofFile.getOriginalFilename();
            newProofFileName = FilenameUtils.getBaseName(proofFile.getOriginalFilename()).concat(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())) + "." + FilenameUtils.getExtension(proofFile.getOriginalFilename());
            MultipartFile multipartFile = new MockMultipartFile(newProofFileName, newProofFileName, proofFile.getContentType(), proofFile.getInputStream());
            list.add(multipartFile);
        }

        // String proofDescFileName = "";
        // String newProofDescFile = "";
        // if (proofDesc != null && !proofDesc.isEmpty()) {
        //     proofDescFileName = proofDesc.getOriginalFilename();
        //     newProofDescFile = FilenameUtils.getBaseName(proofDesc.getOriginalFilename()).concat(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())) + "." + FilenameUtils.getExtension(proofDesc.getOriginalFilename());
        //     MultipartFile multipartFile = new MockMultipartFile(newProofDescFile, newProofDescFile, proofDesc.getContentType(), proofDesc.getInputStream());
        //     list.add(multipartFile);
        // }

        // String ownershipDescName = "";
        // String newOwnershipDescName = "";
        // if (ownershipDesc != null && !ownershipDesc.isEmpty()) {
        //     ownershipDescName = ownershipDesc.getOriginalFilename();
        //     newOwnershipDescName = FilenameUtils.getBaseName(ownershipDesc.getOriginalFilename()).concat(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())) + "." + FilenameUtils.getExtension(ownershipDesc.getOriginalFilename());
        //     MultipartFile multipartFile = new MockMultipartFile(newOwnershipDescName, newOwnershipDescName, ownershipDesc.getContentType(), ownershipDesc.getInputStream());
        //     list.add(multipartFile);
        // }

        String imageFileName = "";
        String newImageFileName = "";
        if (imageFile != null && !imageFile.isEmpty()) {
            imageFileName = imageFile.getOriginalFilename();
            newImageFileName = FilenameUtils.getBaseName(imageFile.getOriginalFilename()).concat(new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date())) + "." + FilenameUtils.getExtension(imageFile.getOriginalFilename());
            MultipartFile multipartFile = new MockMultipartFile(newImageFileName, newImageFileName, imageFile.getContentType(), imageFile.getInputStream());
            list.add(multipartFile);
        }

        if (CollectionUtils.isNotEmpty(list)) {
            MultipartFile[] files = new MultipartFile[list.size()];
            for (int i = 0, listSize = list.size(); i < listSize; i++) {
                MultipartFile item = list.get(i);
                files[i] = item;
            }

            toolsService.batchUpload(files, bucketName);
        }

        // 数据文件大小
        long size = 0l;
        if (dataFile != null) {
            size = dataFile.getSize();// 字节
        }

        double dataFileSizeMb = new BigDecimal(size)
                .divide(new BigDecimal("1024"), 10, RoundingMode.DOWN)
                .divide(new BigDecimal("1024"), 2, RoundingMode.DOWN).doubleValue();
        dataResourceService.saveDataResource(dataResourceName, proprietorshipStatus.name(),
                originalDataFileName, newDataFileName, originalProofFileName, newProofFileName, newImageFileName,
                userId, dataFileSizeMb, price, dataType, dataCategory, proofType, description,usageRightDetail);
        return HttpResponse.resultSuccess();
    }


    @PutMapping("/dataResource")
    @ApiOperation("数据资源创建后进行审核数据资源")
    public HttpResponse auditDataResource(@ApiParam(value = "数据资源ID", required = true) @RequestParam Integer id,
                                          @ApiParam(value = "所有权状态，状态参考创建时的状态列表", required = true) @RequestParam ProprietorshipStatusEnum proprietorshipStatus) {

       return HttpResponse.resultSuccess(dataResourceService.auditDataResource(id, proprietorshipStatus));
    }

    @PutMapping("/userResourceApply/{resourceId}/{userId}")
    @ApiOperation("用户购买后人工审核申请数据资源")
    public HttpResponse auditUserResourceApply(@ApiParam(value = "数据资源ID", required = true) @PathVariable("resourceId") Integer resourceId,
                                               @ApiParam(value = "用户ID", required = true) @PathVariable("userId") Long userId,
                                               @ApiParam(value = "审核通过与否", required = true) @RequestParam Boolean status) {

        // 审核或者重新审核
        dataResourceService.auditUserResourceApply(resourceId, userId, status);
        return HttpResponse.resultSuccess();
    }

    @PutMapping("/platform/userResourceApply/{resourceId}/{userId}")
    @ApiOperation("人工审核通过后，平台再次审核申请数据资源")
    public HttpResponse platformAuditUserResourceApply(@ApiParam(value = "数据资源ID", required = true) @PathVariable("resourceId") Integer resourceId,
                                                       @ApiParam(value = "用户ID", required = true) @PathVariable("userId") Long userId
    ) {

        // 审核或者重新审核
        dataResourceService.platformAuditUserResourceApply(resourceId, userId);
        return HttpResponse.resultSuccess();
    }

    @PostMapping("/userResourceApply")
    @ApiOperation("用户购买进行申请数据资源")
    public HttpResponse applyUserResourceApplication(@ApiParam(value = "数据资源ID", required = true) @RequestParam Integer resourceId,
                                                     @ApiParam(value = "用户Id", required = true) @RequestParam Long userId,
                                                     @ApiParam(value = "申请注释", required = true) @RequestParam String applyNote,
                                                     @ApiParam(value = "使用权明细", required = true) @RequestParam String usageRightDetail,
                                                     @ApiParam(value = "开始", required = true) @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date startTime,
                                                     @ApiParam(value = "结束", required = true) @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) Date endTime) {

        // 申请或者重新申请
        try {

            dataResourceService.applyUserResourceApplication(resourceId, userId, applyNote,usageRightDetail,startTime,endTime);
            return HttpResponse.resultSuccess();
        } catch (AclomeCloudPlatformException e) {
            return HttpResponse.resultError(500, e.getErrorMsgLocal());
        }
    }

    @GetMapping("/dataResource")
    @ApiOperation("分页查询数据资源")
    public HttpResponse<ResponsePage<DataResourceDTO>> auditDataResource(@ApiParam(value = "当前页", required = true) @RequestParam Integer pageNo,
                                                                         @ApiParam(value = "每页查询数量", required = true) @RequestParam Integer pageSize,
                                                                         @ApiParam(value = "所有权状态") @RequestParam(required = false) ProprietorshipStatusEnum proprietorshipStatus,
                                                                         @ApiParam(value = "申请状态") @RequestParam(required = false) ResourceApplyStatusEnum resourceApplyStatusEnumStatus,
                                                                         @ApiParam(value = "分类", required = false) @RequestParam(required = false) String category,
                                                                         @ApiParam(value = "分类", required = false) @RequestParam(required = false) String type,
                                                                         @ApiParam(value = "用户Id", required = true) @RequestParam Long userId) {

        return HttpResponse.resultSuccess(dataResourceService.listDataResource(pageNo,
                pageSize,
                proprietorshipStatus,
                resourceApplyStatusEnumStatus,
                category,
                type,
                userId));
    }

    @GetMapping("/dataShareResource")
    @ApiOperation("数据共享用，没有交易相关的流程")
    public HttpResponse<ResponsePage<DataResourceDTO>> dataShareResource(@ApiParam(value = "当前页", required = true) @RequestParam Integer pageNo,
                                                                         @ApiParam(value = "每页查询数量", required = true) @RequestParam Integer pageSize,
                                                                         @ApiParam(value = "所有权状态") @RequestParam(required = false) ProprietorshipStatusEnum proprietorshipStatus,
                                                                         @ApiParam(value = "分类", required = false) @RequestParam(required = false) String category,
                                                                         @ApiParam(value = "分类", required = false) @RequestParam(required = false) String type) {
        return HttpResponse.resultSuccess(dataResourceService.listDataShareResource(pageNo, pageSize, proprietorshipStatus, category, type));
    }

    @GetMapping("/dataResource/{resourceId}")
    @ApiOperation("根据id查询数据资源")
    public HttpResponse<DataResourceDTO> dataResourceWithId(@ApiParam(value = "当前页", required = true) @PathVariable("resourceId") Integer resourceId) {

        return HttpResponse.resultSuccess(dataResourceService.dataResourceWithId(resourceId));
    }

    @GetMapping("/download")
    @ApiOperation("下载资源文件")
    public void downloadDataResourceFile(@ApiParam(value = "id", required = true) @RequestParam Integer id,
                                         @ApiParam(value = "下载文件类型", required = true) @RequestParam DataResourceFileType fileType
            , HttpServletResponse response) throws IOException {
        dataResourceService.downloadFile(id, fileType, bucketName, response);
    }

    @GetMapping("/dataResource/dict/{dictType}")
    @ApiOperation("查询数据资源类型列表")
    public HttpResponse dataResourceDictList(@PathVariable("dictType") String dictType) {
        return HttpResponse.resultSuccess(dataResourceService.listDataResourceDict(dictType));
    }

    @GetMapping("/userResourceApplyList")
    @ApiOperation("分页查询已申请的数据资源")
    public HttpResponse<ResponsePage<UserResourceApplyDTO>> userResourceApplyList(@ApiParam(value = "当前页", required = true) @RequestParam Integer pageNo,
                                                                                  @ApiParam(value = "每页查询数量", required = true) @RequestParam Integer pageSize,
                                                                                  @ApiParam(value = "申请状态") @RequestParam(required = false) ResourceApplyStatusEnum resourceApplyStatusEnumStatus
    ) {

        return HttpResponse.resultSuccess(dataResourceService.userResourceApplyList(pageNo,
                pageSize,
                resourceApplyStatusEnumStatus));
    }

    @GetMapping("/getConsultationProcess")
    @ApiOperation("获取磋商过程数据")
    public HttpResponse getConsultationProcess() {
        return HttpResponse.resultSuccess(kt1Service.getConsultationProcess());
    }

    @GetMapping("/consultationProcess")
    @ApiOperation("获取磋商过程数据v1.1")
    public HttpResponse<List<ConsultProcessDTO>> getConsultationProcessNew() {
        return HttpResponse.resultSuccess(consultProcessService.getConsultationProcessNew());
    }

    @PostMapping("/consultationProcess")
    @ApiOperation("保存磋商过程数据")
    public HttpResponse saveConsultProcess(@RequestBody ConsultProcessRequest consultProcessRequest) {
        consultProcessService.saveConsultationProcess(consultProcessRequest);
        return HttpResponse.resultSuccess();
    }

    @GetMapping("/getInfo")
    @ApiOperation("保存磋商过程数据")
    public Object getInfo(@RequestParam String id) {
        DataResourceDTO dataResourceDTO = dataResourceService.dataResourceWithId(Integer.valueOf(id));
        return dataResourceDTO;
    }


}
